const https = require('https');
const fs = require('fs');
const path = require('path');
const args = process.argv.slice(2);
let imgPath = [];
//图片后缀
let imgSuffix = ['.jpg', '.png'];
let getImgUrl = (item) => {
    //判断是否是文件夹
    let isDir = fs.statSync(item).isDirectory();
    let ext= path.parse(item).ext;
    if (imgSuffix.includes(ext)) {
        imgPath.push(item);
    } else if(isDir){
        //判断是否是文件夹路径
        const files = fs.readdirSync(item);
        files.forEach((file) => {
            getImgUrl(item + '/' + file)
        })
    }
};
args.forEach((item) => {
    getImgUrl(path.normalize(item))
});
console.log('图片数量', imgPath.length);

class ImageCompressor {

    // 获取请求选项
    getAjaxOptions() {
        return {
            method: 'POST',
            hostname: 'tinify.cn',
            path: '/backend/opt/shrink',
            headers: {
                rejectUnauthorized: false,
                "X-Forwarded-For": Array(4).fill(1).map(() => parseInt(Math.random() * 254 + 1)).join('.'),
                'Postman-Token': Date.now(),
                'Cache-Control': 'no-cache',
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
            }
        };
    }

    /**文件上传*/
    fileUpload(imgPath) {
        return new Promise((resolve, reject) => {
            const imgBuffer = fs.readFileSync(imgPath);
            const req = https.request(this.getAjaxOptions(), (res) => {
                let data = '';
                res.on('data', chunk => {
                    data += chunk;
                });
                res.on('end', () => {
                    try {
                        const obj = JSON.parse(data);
                        if (obj.error) {
                            reject(`压缩失败！\n 当前文件：${imgPath} \n ${obj.message}`);
                        } else {
                            resolve({ imgPath, obj });
                        }
                    } catch (error) {
                        reject(`解析响应错误: ${error}`);
                    }
                });
            });

            req.on('error', (e) => {
                reject(`请求错误! \n 当前文件：${imgPath} \n ${e.message}`);
            });

            req.write(imgBuffer, 'binary');
            req.end();
        });
    }
    /**下载并保存图片 */
    downloadImage(url, savePath) {
        return new Promise((resolve, reject) => {
            const file = fs.createWriteStream(savePath);

            https.get(url, (response) => {
                // 检查响应状态码
                if (response.statusCode === 200) {
                    response.pipe(file);  // 将响应数据直接写入文件
                    file.on('finish', () => {
                        resolve('图片下载并保存成功!');
                    });
                } else {
                    reject(`下载失败，状态码: ${response.statusCode}`);
                }
            }).on('error', (err) => {
                reject(`请求错误: ${err.message}`);
            });
        });
    }

    async task() {
        console.log('开始压缩图片');
        let prop = [];
        for (let i = 0; i < imgPath.length; i++) {
            const img = imgPath[i];
            try {
                prop.push(new Promise(async (resolve, reject) => {
                    let imageInfo = await this.fileUpload(img);
                    // 获取压缩后的图片 URL
                    const compressedImageUrl = imageInfo.obj.output.url;
                    // 获取 imgPath
                    const imgPath = imageInfo.imgPath;  // 保存图片的路径
                    // 调用函数下载图片并保存到 imgPath
                    await this.downloadImage(compressedImageUrl, imgPath)
                    console.log(`图片压缩完成: ${imgPath} ${imageInfo.obj.input.size} ---> ${imageInfo.obj.output.size}`);
                    resolve();
                }))
            } catch (error) {
                console.log('图片报错', img, error);
            }

        }

        await Promise.all(prop).then(() => {
            console.log('压缩完成');
        }).catch((error) => {
            console.log('压缩失败', error);
        });

        await new Promise((resolve) => {
            setTimeout(() => {
                resolve();
            },3000);
        });
    }

}

const compressor = new ImageCompressor();
compressor.task()

// pkg打包时要管理员权限
// pkg -t node18-win-x64 index.js
//pkg index.js --debug --targets node18-win-x64